import db from '../../utils/dbconf';
import makeres from '../../utils/res';
import { ParameterError, AuthError } from '../../utils/classModal';
import { TABLE_NAME as AUTH_DICT_TABLE } from './auth';
import { TABLE_NAME as USER_TABLE } from '../user';
import { TABLE_NAME as CARD_TABLE } from '../mjconf/cardcrud';
import { TABLE_NAME as GROUP_TABLE } from '../mjconf/groupcrud';

export const TABLE_NAME = 'RELACTION_USER_AUTH';

export const get_user_auth = async (u_id) => {
	const auth = await db
		.table(TABLE_NAME)
		.alias('t')
		.where({ u_id, active: 1 })
		.field('t.id,auth_id,effective,weight,name,cards_num,deck_num,user_num') //
		.join({
			table: AUTH_DICT_TABLE,
			join: 'left',
			as: 'dict',
			on: ['auth_id', 'dict.id'],
		})
		.find();
	return auth;
};

export const get_user_auth_use = async (u_id) => {
	const list = [USER_TABLE, CARD_TABLE, GROUP_TABLE].map((tablename) =>
		db.table(tablename).where({ u_id }).count('id')
	);
	const [user_num, cards_num, deck_num] = await Promise.all(list);
	return { user_num, cards_num, deck_num };
};

export const get_user_auth_list = async (u_id) => {
	const records = await db.table(TABLE_NAME).field('u_id,createtime,updatetime', true).where({ u_id }).select();
	return records;
};

const ugetauth = async ({ query: { commond } }, res) => {
	const { u_id } = res.locals;
	let resdata;
	if (commond === 'get') {
		resdata = await get_user_auth(u_id);
	} else if (commond === 'getuse') {
		resdata = await get_user_auth_use(u_id);
	} else if (commond === 'getlist') {
		resdata = await get_user_auth_list(u_id);
	} else {
		throw new ParameterError();
	}
	return res.send(makeres.success(resdata));
};

const supermake = async ({ params: { u_id, auth_id, effective } }, res, next) => {
	if (!Number(u_id) || !Number(auth_id) || !effective) throw new ParameterError();
	const { level } = res.locals;
	if (level !== 999) throw new AuthError();
	const resdata = await additem(u_id, auth_id, effective);
	return res.send(makeres.success({ auth: resdata }, '添加成功'));
};

/**
 *
 * 创建一条用户VIP关系 - 并完成订单
 */
const additem = async (u_id, auth_id, effective) => {
	// 先把权限加上
	const addok = await db.table(TABLE_NAME).where({ u_id, auth_id }).updateInc('effective', effective);
	if (!addok) await db.table(TABLE_NAME).add({ u_id, auth_id, effective });
	// 切换最高权限为使用状态
	const u_auth = await db
		.table(TABLE_NAME)
		.alias('a')
		.field('a.id,auth_id,effective,weight,name')
		.join({
			table: AUTH_DICT_TABLE,
			as: 'b',
			join: 'left',
			on: ['auth_id', 'id'],
		})
		.where({ u_id, effective: ['>', 0] })
		.order('weight DESC')
		.select();
	const new_acitve = u_auth[0]; // weight - desc
	await db
		.table(TABLE_NAME)
		.where({ id: ['IN', u_auth.map(({ id }) => id)] })
		.update({ active: ['EXP', `(id = ${new_acitve.id})`] });
	return new_acitve;
};

const dailytask = async () => {
	// VIP天数 - 1
	const dec = await db.table(TABLE_NAME).where({ active: 1 }).updateDec('effective', 1);
	// 删除失效的VIP记录 ：将符合条件的active改为0
	const off = await db
		.table(TABLE_NAME)
		.where({
			effective: ['<=', 0],
			active: ['!=', 0],
		})
		.update({ active: 0 });
	// 为“仍有其他VIP”的人“开通”其中“权重最大”的VIP
	const update_data = await db.query(`
		SELECT u_id,id AS auth_id FROM 
		(
			SELECT u_id,MAX(weight) AS weight
			FROM ${TABLE_NAME} 
			left JOIN ${AUTH_DICT_TABLE} AS dict
				ON auth_id = dict.id
			WHERE effective > 0
			GROUP BY u_id
			HAVING MAX(\`active\`) = 0
		)AS a
		LEFT JOIN ${AUTH_DICT_TABLE} AS b
		ON a.weight = b.weight
	`);
	if (!update_data.length) return { dec, off, be_active: [] };
	for (let where of update_data) await db.table(TABLE_NAME).where(where).update({ active: 1 });
	// 提交任务日志
	console.log(new Date().toLocaleDateString(), '每日任务已完成');

	return { dec, off, be_active: update_data };
};

// 解决this指向问题
export default {
	ugetauth,
	supermake,
	additem,
	dailytask,
};
